package com.sh.cathtml.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.sh.suhe.utildemos.R
import com.sh.suhe.utildemos.model.MainModel
import java.util.ArrayList



class MainAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var datas = ArrayList<MainModel>()
    lateinit var onClick:OnClick
    override fun onCreateViewHolder(p0: ViewGroup, viewType: Int): RecyclerView.ViewHolder {

        if (viewType == 1){
           val titleView = LayoutInflater.from(p0.context).inflate(R.layout.adapter_main_title,null)
            return TitleViewHolder(titleView)
        }else{
            val view = LayoutInflater.from(p0.context).inflate(R.layout.adapter_main_item,null)
            return ViewHolder(view)
        }
    }
    override fun getItemViewType(position: Int): Int {
        return if(datas[position].isTitle)   1 else 2
    }
    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, p1: Int) {
        (viewHolder as TypeAbstartViewHolder).bindHolder(datas[p1],onClick)
    }


    class ViewHolder(itemView: View) : TypeAbstartViewHolder(itemView) {
        override fun bindHolder(item: MainModel,onClick:OnClick) {
            title.text = item.title
            title.setOnClickListener { onClick.toArticle(item) }
        }

        var title:TextView = itemView.findViewById(R.id.main_item_title)
    }
    class TitleViewHolder(itemView: View) : TypeAbstartViewHolder(itemView) {
        override fun bindHolder(item: MainModel,onClick:OnClick) {
            title.text = item.title
        }
        var title:TextView = itemView.findViewById(R.id.main_title_name)
    }
    abstract   class TypeAbstartViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        abstract fun bindHolder(item: MainModel,onClick:OnClick)
    }

    fun notifyDataSetChanged(datas:List<MainModel>,title:String){
        if ( datas.isNotEmpty()){
            val model = MainModel(title,"")
            model.isTitle = true
            this.datas.add(model)
            this.datas.addAll(datas)
            notifyDataSetChanged()
        }
    }
    interface OnClick{
        fun toArticle(item: MainModel)
    }
}